﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace Handrise.CDCable.Business
{
    public class UpdateService
    {
        public bool GetNeedUpdate(string clientVersion,out long fileLen,out string serverVersion)
        {
            fileLen = 0;
            serverVersion = "";

            //查询服务器上的程序版本
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(CommonFunction.GetLocalPath() + "\\Update\\Update.xml");
            XmlNode xmlNode = CommonFunction.GetXmlNode(xmlDoc, "Configuration/Info");

            if (xmlNode == null)
                return false;

            string fileName = CommonFunction.GetLocalPath() + "\\Update\\update.udd"  ;

            serverVersion = xmlNode.Attributes["Version"].Value;

            bool needUpdate = double.Parse(serverVersion) > double.Parse(clientVersion);

            if (needUpdate)
            {
                FileInfo fi = new FileInfo(fileName);
                fileLen = fi.Length;
            }

            return needUpdate;
        }

        /// <summary>
        /// 同步升级数据
        /// </summary>
        /// <param name="beginIndex">开始索引</param>
        /// <param name="buffer">返回的数据流</param>
        public bool SynchronizeUpdateData(int beginIndex, out byte[] buffer)
        {
            string fileName = CommonFunction.GetLocalPath() + "\\Update\\update.udd"  ;
            FileStream fs = new FileStream(fileName,FileMode.Open,FileAccess.Read,FileShare.Read);
            int len ;
            if ((fs.Length - 1024 * 100 * beginIndex) > 1024 * 100)
                len = 1024 * 100;
            else
                len = (int)fs.Length - 1024 * 100 * beginIndex;

            buffer = new byte[len];

            fs.Position = 1024 * 100 * beginIndex;
            fs.Read(buffer,0, len);
            fs.Close();

            return true;
        }
    }
}
